<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddBrandShopToWaimai extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('waimai_order_details', function (Blueprint $table) {
            $table->unsignedInteger('shopId')->default(0)->after('id');
            $table->unsignedInteger('brandId')->default(0)->after('id');

            $table->index('shopId', 'idx_shopId');
        });

        \App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel::query()
                                                      ->groupBy('orderId')
                                                      ->select('orderId')
                                                      ->get()
                                                      ->each(function ($item) {
                                                          $shopId = (int)\App\Kuafu\WaiMai\Model\WaiMaiOrderModel::query()
                                                                                                                 ->where('orderId',
                                                                                                                     $item->orderId)
                                                                                                                 ->value('shopId');
                                                          if ($shopId) {
                                                              \App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel::query()
                                                                                                            ->where('orderId',
                                                                                                                $item->orderId)
                                                                                                            ->update([
                                                                                                                'shopId'  => $shopId,
                                                                                                                'brandId' => 1
                                                                                                            ]);

                                                              dump('WaiMaiOrderDetail shopId Update...'.$item->orderId);
                                                          }
                                                      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('waimai_order_details', function (Blueprint $table) {
            $table->dropColumn('shopId');
            $table->dropColumn('brandId');
        });
    }
}
